package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Flight;

/**
 * Servlet implementation class RemoveFromCart
 */
public class RemoveFromCart extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RemoveFromCart() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}


	/**
	 * The doPost method gets flight id to remove from the ajax request.
	 * The cart is iterated through and the correct flight is removed. A 
	 * message is returned about the removal status.
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get session object
		HttpSession session = request.getSession();

		//Get flight id from parameter
		int flightID = Integer.parseInt(request.getParameter("flightID"));

		//Get cart
		ArrayList<Flight> cart = (ArrayList<Flight>) session.getAttribute("shoppingCart");
		
		//Remove flight
		boolean removed = false;
		for(int i=0; i<cart.size(); i++){
			Flight flight = cart.get(i);
			if(flight.getId() == flightID){
				removed = cart.remove(flight);
			}
		}
		
		//Return message
		if(removed){
			response.getWriter().write("removed");
		} else {
			response.getWriter().write("notRemoved");
		}

	}

}
